<script setup lang="ts">
import {
    NButton, NModal, NFlex, NSelect,
    NForm, NFormItem, NCascader, type FormInst,
    type CascaderOption,
    type SelectOption
} from 'naive-ui';

import { useFeature } from "~/common/mixins/";
import { type VillageAllocation } from '@/apis/models';
import { useMessage } from "naive-ui";
import { reactive, ref, type VNodeChild } from 'vue';
import { useVillageStore } from "@/store";
let villageStore = useVillageStore();

let { UpdateOne } = useFeature();

let message = useMessage();
let ruleFormRef = ref<FormInst>();
let emits = defineEmits(["handleQuery"])

let state = reactive({
    ruleForm: {} as VillageAllocation,
    showModal: false,
    loading: false
})

let fdVillage = ref();
let labelWidth = ref(80)
let formRules = ref({
    fdRegion: [
        { required: true, message: '区域必选', trigger: 'blur' }
    ],
    fdVillage: [
        { required: true, message: '物业小区必选', trigger: 'blur' }
    ]
})


let onSubmit = (e: MouseEvent) => {
    e.preventDefault()
    ruleFormRef.value?.validate((errors) => {
        if (!errors) {
            let f = state.ruleForm;
            UpdateOne(villageStore, f).then((res: any) => {
                if (res.code == 200) {
                    message.success("数据修改成功");
                    state.showModal = false;
                    closeDialog();
                }
            })
        }
        else {
            console.log(errors)
        }
    })
}

function openDialog(row: any) {
    loadRegion();
    state.ruleForm = JSON.parse(JSON.stringify(row));
    state.showModal = true;
}

let closeDialog = () => {
    emits('handleQuery');
    state.showModal = false;
}

let regionOptions = ref();
let loadRegion = () => {
    villageStore.takeRegions().then((res: any) => {
        regionOptions.value = res.data;
    })
}


let secondCity = ref();
let handleRegion = (_: string, __: CascaderOption, pathValues: Array<CascaderOption>) => {
    let province = pathValues[0].label;
    let city = pathValues[1].label;
    let community = pathValues[2].label;
    let regions = regionOptions.value;
    row: for (let i = 0; i < regions.length; i++) {
        let provinceName = regions[i].label;
        if (provinceName == province) {
            let citys = regions[i].children;
            for (let j = 0; j < citys.length; j++) {
                let cityName = citys[j].label;
                if (cityName == city) {
                    let communities = citys[j].children;
                    for (let k = 0; k < communities.length; k++) {
                        let communityName = communities[k].label;
                        if (communityName == community) {
                            secondCity.value = city;
                            state.ruleForm.fdRegion = communityName;
                            state.ruleForm.fdRegionLat = communities[k].lat;
                            state.ruleForm.fdRegionLng = communities[k].lng;
                            state.ruleForm.fdProvince = provinceName;
                            state.ruleForm.fdCity = cityName;
                            break row;
                        }
                    }
                }
            }
        }
    }

    console.log(state.ruleForm);
}

let handleVillage = (_: Array<string>, option: SelectOption) => {
    state.ruleForm.fdVillage = option.name as string;
    let loc = option.location as string;
    let locs = loc.split(",")
    state.ruleForm.fdVillageLng = locs[0];
    state.ruleForm.fdVillageLat = locs[1];
    state.ruleForm.fdVillageAddress = option.address as string;
}

let villages = ref();
let loading = ref(false);
let handleSearch = (query: string) => {
    if (!state.ruleForm.fdRegion) {
        message.error("先选择区域");
        state.ruleForm.fdVillage = "";
        return;
    }
    if (query) {
        loading.value = true;
        let form = { city: secondCity.value, citylimit: true, keywords: query, types: '商务住宅' }

        villageStore._inputTip(form).then((res: any) => {
            let datas = res.data;
            villages.value = datas;

            loading.value = false;
        });
    } else {
        villages.value = [];
    }
}

let renderLabel = (option: SelectOption): VNodeChild => {
    return option.name as string
}

defineExpose({ openDialog });
</script>

<template>
    <div class="mc_1">
        <n-modal content-style="padding:10px;" style="width:38%;" title="资源归属" :show-icon="false" :bordered="true"
            v-model:show="state.showModal" preset="dialog">

            <template #default>
                <n-form ref="ruleFormRef" :rules="formRules" :model="state.ruleForm" :label-width="labelWidth"
                    require-mark-placement="left" label-placement="left" label-align="right">
                    <n-form-item :show-require-mark="true" path="fdRegion" label="区域选择">
                        <n-cascader v-model:value="state.ruleForm.fdRegion" placeholder="请选择区域" :options="regionOptions"
                            check-strategy="child" expand-trigger="click" @update:value="handleRegion" />
                    </n-form-item>
                    <n-form-item :show-require-mark="true" path="fdVillage" label="小区名称">
                        <n-select placeholder="请选择小区名称" :loading="state.loading" v-model:value="fdVillage" filterable
                            remote @search="handleSearch" :options="villages" :render-label="renderLabel"
                            @update:value="handleVillage" />
                    </n-form-item>
                    <n-form-item :show-require-mark="true" path="fdVillageAddress" label="小区地址">
                        <n-input v-model:value="state.ruleForm.fdVillageAddress" placeholder="小区地址"></n-input>
                    </n-form-item>
                    <n-form-item>
                        <n-flex style="width:fit-content;position:absolute;right:0;">
                            <n-button type="primary" @click="onSubmit">确定</n-button>
                            <n-button @click="state.showModal = false">取消</n-button>
                        </n-flex>
                    </n-form-item>
                </n-form>
            </template>
        </n-modal>
    </div>

</template>

<style scoped>
.toolbar {
    padding: 10px 0 10px 10px;

    .n-button:first-child {
        margin-right: 10px;
    }
}
</style>
